package service.Impl;


import mapper.Impl.StudentMapperImpl;
import mapper.Impl.TeacherMapperImpl;
import mapper.Impl.adminMapperImpl;
import mapper.StudentMapper;
import mapper.TeacherMapper;
import mapper.adminMapper;
import pojo.User;
import pojo.admin;
import service.UserService;
import utils.CookieUtils;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.sql.SQLException;
import java.util.Random;

public class UserServiceImpl implements UserService {

    private StudentMapper studentMapper = new StudentMapperImpl();
    private TeacherMapper teacherMapper = new TeacherMapperImpl();

    @Override
    public void drawCode(HttpServletRequest request, HttpServletResponse response) {
        //设置宽高的变量
        int width = 120;
        int height = 30;

        //创建画布
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

        //获取画笔
        Graphics graphics = image.getGraphics();

        //设置背景色 -- 填充矩形
        graphics.setColor(Color.BLUE);
        graphics.fillRect(0,0,width,height);

        //设置验证码
        Random random = new Random();
        String[] codes = {"A","B","C","D","E","F","G","H","J","K","M","N","P","Q","R","S","T","U","V","W","X","Y","Z","0","1","2","3","4","5","6","7","8","9"};
        Color[] colors = {Color.CYAN,Color.BLACK,Color.GREEN,Color.PINK,Color.WHITE,Color.RED,Color.ORANGE};

        StringBuffer sb = new StringBuffer();

        for (int i = 0; i < 4; i++) {

            String randomCode = codes[random.nextInt(codes.length)];
            Color randomColor = colors[random.nextInt(colors.length)];

            graphics.setColor(randomColor);//设置随机颜色
            graphics.setFont(new Font("宋体",Font.BOLD,20+random.nextInt(10)));//设置字体（字体,样式,大小）
            graphics.drawString(randomCode,20+i*25,15+random.nextInt(10));//设置单个验证码

            sb.append(randomCode);
        }

        //将系统验证码设置到Session对象中(会话对象)
        HttpSession session = request.getSession();//获取请求里的JSESSIONID(客户端Cookie里的数据)，如果没有就创建Session对象，如果有就从Session容器中获取会话对象
        session.setAttribute("sysCode",sb.toString());

        //设置干扰线
        graphics.setColor(Color.YELLOW);
        for (int i = 0; i < 3; i++) {
            graphics.drawLine(random.nextInt(width),random.nextInt(height),random.nextInt(width),random.nextInt(height));//绘制直线(x1,y1,x2,y2) -> 两点为一线
        }

        //将画布以jpg形式的文件传出给客户端
        try {
            ImageIO.write(image,"jpg",response.getOutputStream());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public String login(HttpServletRequest request, HttpServletResponse response) throws SQLException {
        //获取请求中的数据
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String userCode = request.getParameter("userCode");
        String rememberMe = request.getParameter("rememberMe");
        String role = request.getParameter("role");

        //从Session对象中获取系统的验证码
        String sysCode = (String) request.getSession().getAttribute("sysCode");
        if(sysCode.equalsIgnoreCase(userCode)){//验证码正确

            User user = null;
            admin admin = null;
            if("student".equals(role)){
                user = studentMapper.getStudent(username,password);
            }else if("teacher".equals(role)){
                user = teacherMapper.getTeacher(username,password);
            }else if("admin".equals(role)){
                adminMapper adminMapper = new adminMapperImpl();
                admin = adminMapper.getAdmin(username,password);
            }

            if(user != null){//登录成功

                //判断是否记住我
                if(rememberMe != null){
                    rememberMe(response,user.getUsername(),user.getName() ,role,user.getPhoto());
                }

                //将数据存储到Session中
                HttpSession session = request.getSession();
                session.setAttribute("user",user);
                session.setAttribute("role",role);

                return "1";
            }else{
                if(admin != null){//admin登陆成功
                    if(rememberMe != null){
                        rememberMe(response,admin.getUsername(),null ,role,null);
                    }

                    HttpSession session = request.getSession();
                    session.setAttribute("user",admin);
                    session.setAttribute("role",role);


                    return "2";
                }else{//登录失败 -- 账号或密码错误
                    return "-1";
                }

            }

        }else{//登录失败 - 验证码错误
            return "-2";
        }
    }

    @Override
    public void rememberMe(HttpServletResponse response,String username, String name, String role, String photo) {
        //将凭证添加到Cookie中
        if(username != null){
            response.addCookie(CookieUtils.createCookie("username",username,60*60*24*5));
        }
        if(name != null){
            response.addCookie(CookieUtils.createCookie("name",name,60*60*24*5));
        }
        if(role != null){
            response.addCookie(CookieUtils.createCookie("role",role,60*60*24*5));
        }
        if(photo != null){
            response.addCookie(CookieUtils.createCookie("photo",photo,60*60*24*5));
        }

    }

    @Override
    public void loginOut(HttpServletRequest request, HttpServletResponse response) {
        //删除Cookie里的数据
        response.addCookie(CookieUtils.createCookie("username","",0));
        response.addCookie(CookieUtils.createCookie("name","",0));
        response.addCookie(CookieUtils.createCookie("role","",0));
        response.addCookie(CookieUtils.createCookie("photo","",0));

        //删除Session里的数据
        HttpSession session = request.getSession();
        session.removeAttribute("username");
        session.removeAttribute("name");
        session.removeAttribute("role");
        session.removeAttribute("photo");
    }

    @Override
    public boolean resetPassword(HttpServletRequest request, HttpServletResponse response) throws SQLException {
        String role = (String) request.getSession().getAttribute("role");
        if("admin".equals(role)){
            admin admin = (pojo.admin) request.getSession().getAttribute("user");
            String username = admin.getUsername();
            //前端填的password
            String password = request.getParameter("password");
            //Session里面的password
            String passWord = admin.getPassword();
            String newPassword = request.getParameter("newPassword");
            if(passWord.equals(password)){
                adminMapper adminMapper = new adminMapperImpl();
                adminMapper.updatePassword(username,newPassword);
                return true;

            }else{
                return false;
            }
        }else{
            //获取请求中的数据
            User user = (User) request.getSession().getAttribute("user");
            String username = user.getUsername();
            //前端填的password
            String password = request.getParameter("password");
            //Session里面的password
            String passWord = user.getPassword();
            String newPassword = request.getParameter("newPassword");
            if(passWord.equals(password)){
                if ("student".equals(role)) {
                    studentMapper.update(username, newPassword);
                } else if ("teacher".equals(role)) {
                    teacherMapper.update(username, newPassword);
                }
                return true;
            }
            else{
                return false;
            }
        }

    }
}
